package com.southminority.ethnic.controller.admin.research;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.ResearchProject;
import com.southminority.ethnic.service.research.ResearchProjectService;
import com.southminority.ethnic.controller.research.vo.ResearchProjectVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 科研项目管理后台控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "19 - 科研项目管理API", description = "【后台】科研成果-科研项目的增删改查接口")
@RestController
@RequestMapping({"/admin/research/project", "/admin/research/projects"})
@CrossOrigin
public class ResearchProjectAdminController {

    private final ResearchProjectService researchProjectService;

    public ResearchProjectAdminController(ResearchProjectService researchProjectService) {
        this.researchProjectService = researchProjectService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页和条件查询科研项目", description = "后台管理使用的项目列表接口，支持多种条件筛选和分页。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "查询成功")})
    public R<PageResult<ResearchProjectVO>> getResearchProjectPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关键词（标题、负责人）", example = "语言智能") @RequestParam(required = false) String keyword,
            @Parameter(description = "项目类型", schema = @Schema(type = "string", allowableValues = {"ongoing", "completed", "planning"})) @RequestParam(required = false) String projectType,
            @Parameter(description = "项目级别", example = "国家级") @RequestParam(required = false) String level,
            @Parameter(description = "状态", example = "1", schema = @Schema(type = "integer", allowableValues = {"1", "0"})) @RequestParam(required = false) Integer status) {
        return R.ok(researchProjectService.getProjectPageForAdmin(page, size, keyword, projectType, level, status));
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取单个科研项目的详细信息（用于编辑）", description = "根据项目ID查询，返回其完整信息，包括JSON字段解析后的数组。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "项目不存在")
    })
    public R<ResearchProjectVO> getResearchProjectById(@Parameter(description = "科研项目ID", example = "1", required = true) @PathVariable Long id) {
        return R.ok(researchProjectService.getProjectDetailForAdmin(id));
    }

    @PostMapping("/create")
    @Operation(summary = "新增一个科研项目", description = "传入项目的完整信息（除ID外）来创建一个新的记录。注意：JSON字段应为字符串格式。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "创建成功")})
    public R<ResearchProjectVO> createResearchProject(@RequestBody(description = "科研项目信息的JSON对象", required = true,
            content = @Content(schema = @Schema(implementation = ResearchProject.class)))
            @org.springframework.web.bind.annotation.RequestBody ResearchProject project) {
        log.info("管理员创建科研项目: {}", project.getTitle());
        return R.ok(researchProjectService.createProject(project));
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "根据ID更新科研项目信息", description = "提供项目ID和更新后的信息，对现有记录进行修改。注意：JSON字段应为字符串格式。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "404", description = "项目不存在")
    })
    public R<ResearchProjectVO> updateResearchProject(
            @Parameter(description = "要更新的项目ID", example = "1", required = true) @PathVariable Long id,
            @RequestBody(description = "包含更新字段的项目JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = ResearchProject.class)))
                    @org.springframework.web.bind.annotation.RequestBody ResearchProject project) {
        log.info("管理员更新科研项目: ID={}, Title={}", id, project.getTitle());
        return R.ok(researchProjectService.updateProject(id, project));
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "根据ID逻辑删除科研项目", description = "将指定ID的项目记录状态设置为-1（已删除）。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "删除成功")})
    public R<Boolean> deleteResearchProject(@Parameter(description = "要删除的项目ID", example = "1", required = true) @PathVariable Long id) {
        log.info("管理员删除科研项目: ID={}", id);
        return R.ok(researchProjectService.deleteProject(id));
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量逻辑删除科研项目", description = "传入一个ID列表，批量将对应的项目记录状态设置为-1。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "批量删除成功")})
    public R<Boolean> batchDeleteResearchProject(
            @RequestBody(description = "包含多个项目ID的数组", required = true,
                    content = @Content(schema = @Schema(type = "array", implementation = Long.class)))
                    @org.springframework.web.bind.annotation.RequestBody List<Long> ids) {
        log.info("管理员批量删除科研项目: IDs={}", ids);
        return R.ok(researchProjectService.batchDeleteProjects(ids));
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新科研项目状态", description = "更新单个项目的状态，如启用（1）和禁用（0）。")
    @Parameters({
            @Parameter(name = "id", description = "项目ID", example = "1", required = true),
            @Parameter(name = "status", description = "新的状态值", example = "0", required = true,
                    schema = @Schema(type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "状态更新成功")})
    public R<Boolean> updateResearchProjectStatus(@PathVariable Long id, @RequestParam Integer status) {
        log.info("管理员更新科研项目状态: ID={}, Status={}", id, status);
        return R.ok(researchProjectService.updateProjectStatus(id, status));
    }

    @PutMapping("/featured/{id}")
    @Operation(summary = "设置科研项目重点展示状态", description = "设置或取消单个项目的重点展示状态。")
    @Parameters({
            @Parameter(name = "id", description = "项目ID", example = "1", required = true),
            @Parameter(name = "isFeatured", description = "是否重点展示", example = "1", required = true,
                    schema = @Schema(type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "设置成功")})
    public R<Boolean> setResearchProjectFeatured(@PathVariable Long id, @RequestParam Integer isFeatured) {
        log.info("管理员设置科研项目重点标识: ID={}, IsFeatured={}", id, isFeatured);
        return R.ok(researchProjectService.setProjectFeatured(id, isFeatured));
    }

    /**
     * 获取所有科研项目列表（用于下拉选项）
     */
    @GetMapping("/all")
    @Operation(summary = "获取所有科研项目列表", description = "提供给前端下拉选择用，过滤已删除(status=-1)的数据")
    public R<List<ResearchProjectVO>> getAllProjects() {
        return R.ok(researchProjectService.getAllProjectsForAdmin());
    }

    @GetMapping("/test")
    @Operation(summary = "测试接口连通性")
    public R<String> test() {
        return R.ok("科研项目管理后台服务正常");
    }
} 
